from flask import Flask
from flask_mysqldb import MySQL

from config import Config
from models import db

app = Flask(__name__)
# 关键配置：确保JSON响应使用UTF-8编码且不转义中文字符
app.config['JSON_AS_ASCII'] = False  # 这是最重要的一步
app.config.from_object(Config)
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_recycle': 3600,
    'pool_pre_ping': True,
    'pool_size': 10,
    'max_overflow': 1024,
    'pool_timeout': 30,
}

# 初始化 MySQL
mysql = MySQL(app)

# 初始化 SQLAlchemy ORM
app.config['SQLALCHEMY_DATABASE_URI'] = (
    f"mysql+mysqldb://{app.config['MYSQL_USER']}:{app.config['MYSQL_PASSWORD']}"
    f"@{app.config['MYSQL_HOST']}/{app.config['MYSQL_DB']}"
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)


# 定期检查连接池状态
@app.before_request
def check_db_connection():
    try:
        db.session.execute("SELECT 1")
    except Exception:
        db.session.remove()


# 创建数据库表（首次运行时）
with app.app_context():
    db.create_all()
    print('初始化成功')

# 导入路由
from routes import *

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    # app.run(debug=True, host='0.0.0.0', ssl_context=('yebosean.xyz_bundle.pem', 'yebosean.xyz.key'))
